module key_proc (
    input        clk,             // 系统时钟信号
    input        rst_n,           // 低电平复位信号
    input  [3:0] key_in,          // 4 个按键输入信号
    output [6:0] counter_1,       //计数器1
    output [6:0] counter_2,       //计数器2
    output [1:0] countdown_flag,  //倒计时状态
    output [4:0] countdown        //倒计时
);
    reg  [4:0] countdown_r;
    reg  [1:0] countdown_flag_r;  //0停止 1启动 2暂停
    reg  [6:0] counter_1_r;
    reg  [6:0] counter_2_r;
    wire [3:0] down;  // 每个按键的按下检测信号
    wire [3:0] up;  // 每个按键的松开检测信号
    wire       clk_1;  //1s

    frequency_divider u_frequency_divider1 (
        .clk    (clk),
        .rst_n  (rst_n),
        .clkbase(50_000_000),
        .clkdiv (1),
        .clkout (clk_1)
    );
    wire clk_100;  //10ms
    frequency_divider u_frequency_divider100 (
        .clk    (clk),
        .rst_n  (rst_n),
        .clkbase(50_000_000),
        .clkdiv (100),
        .clkout (clk_100)
    );

    always @(posedge clk_1 or negedge rst_n) begin
        if (!rst_n) begin
            countdown_r <= 5'd20;  //设置倒计时初始值
        end else if (countdown_flag_r == 2'b01) begin
            if (countdown_r != 5'd0) countdown_r <= countdown_r - 1'b1;  //倒计时减1

        end
    end
    // 实例化按键消抖模块 key_ctrl，用于按键消抖处理
    key_ctrl key_ctrl_inst (
        .clk   (clk),     // 系统时钟输入
        .rst_n (rst_n),   // 低电平复位信号
        .key_in(key_in),  // 按键输入信号
        .down  (down),    // 按下检测输出
        .up    (up)       // 松开检测输出
    );

    // 根据按键按下状态控制模式切换
    always @(posedge clk_100 or negedge rst_n) begin
        if (!rst_n) begin
            //设置计数器初始值
            counter_1_r <= 7'd0;
            counter_2_r <= 7'd0;
            //设置倒计时状态
            countdown_flag_r <= 2'b00;

        end else begin
            case (down)
                4'b0001:
                if (countdown_flag == 2'b01 && counter_1_r <= 99) counter_1_r <= counter_1_r + 1'b1;
                4'b0010:
                if (countdown_flag == 2'b01 && counter_2_r <= 99) counter_2_r <= counter_2_r + 1'b1;
                4'b0100:
                case (countdown_flag)
                    2'b00: countdown_flag_r <= 2'b01;  // 启动
                    2'b01: countdown_flag_r <= 2'b10;  // 暂停
                    2'b10: countdown_flag_r <= 2'b01;  // 重新启动
                endcase
            endcase
        end
    end
    assign counter_1 = counter_1_r;
    assign counter_2 = counter_2_r;
    assign countdown_flag = (countdown_r == 0) ? 2'b00 : countdown_flag_r;
    assign countdown = countdown_r;
endmodule
